<?php
declare (strict_types = 1);
/**
 * 管理员角色
 */
namespace app\common\model;

class AdminRole extends BaseModel
{

    public function adminRulehasMany()
    {
        return $this->hasMany(AdminRule::class, 'id');
    }

    /**
     * 角色权限列表
     */
    public function roleAdminList($whereAdmin = [])
    {
        $field = ['id', 'ruleId', 'name', 'description', 'enable'];

        $list = self::field($field)->where($whereAdmin)->order(['id' => 'desc'])->select();
        
        foreach($list as $role){
            if(empty($role->ruleId)) continue;
            $children = self::adminRulehasMany()->field('id, pid, path, auth_name, enable')->where('id', 'in', $role->ruleId)->select()->toArray();
            $role->children = self::treeRuleList($children);
        }
        
        return $list;
    }

    public function treeRuleList($list = [], $root = 0, $id= 'id', $pid = 'pid', $child = 'children')
    {
        $tree = [];

        if($list){
            $refer = [];
            foreach($list as $key => $v){
                $refer[$v[$id]] =& $list[$key];
            }

            foreach($list as $key => $v){
                $parentid = $v[$pid];
                if($root == $parentid) {
                    $tree[] =& $list[$key];                 
                }else{
                    if(isset($refer[$parentid])){
                        $parent =& $refer[$parentid];
                        $parent[$child][] =& $list[$key];
                    }
                }
            }
        }
        return $tree;
    }

    public function getTreeidStr($list = [], $chid = 'children')
    {
        $data = [];
        foreach ($list as &$item){
            $data[] = $item['id'];
            if(isset($item[$chid])){                
                $cate = self::getTreeidStr($item[$chid]);
                if(!empty($cate)){
                    $arr = $cate;                    
                }
                $data = array_merge($data,$arr);                           
            }          
        }
        return $data;      
    }
}
